#include <libbase/dswmemlistbase.h>

CDswmemlistbase::CDswmemlistbase(LPST_ENV_T pEnv)
: CDswbase(pEnv)
{
}

CDswmemlistbase::~CDswmemlistbase()
{
}

int CDswmemlistbase::GetNodeCount(LPST_LIST_MEM_T pList)
{
	int nCount = 0;
	MUTEX_LOCK(&pList->lock);
	nCount = pList->list.size();
	MUTEX_UNLOCK(&pList->lock);
	return nCount;
}

void CDswmemlistbase::PutNodeToList(void* pNode, LPST_LIST_MEM_T pList)
{
	MUTEX_LOCK(&pList->lock);
	pList->list.push_back(pNode);
	MUTEX_UNLOCK(&pList->lock);
}

void CDswmemlistbase::PutNodeToListFront(void* pNode, LPST_LIST_MEM_T pList)
{
	MUTEX_LOCK(&pList->lock);
	pList->list.push_front(pNode);
	MUTEX_UNLOCK(&pList->lock);
}

void* CDswmemlistbase::GetNodeFromList(LPST_LIST_MEM_T pList)
{
	void* pNode = NULL;
	MUTEX_LOCK(&pList->lock);
	if (!pList->list.empty()){
		pNode = pList->list.front();
		pList->list.pop_front();
	}
	MUTEX_UNLOCK(&pList->lock);
	return pNode;
}

bool CDswmemlistbase::CopyNodeFromList(LPST_LIST_MEM_T pList, void* pDest, EN_FRAME_TYPE nType)
{
	bool bRet = false;
	if (nType == TYPE_AUDIO_FRAME){
		LPST_AUDIO_FRAME_T pFrame = (LPST_AUDIO_FRAME_T)pDest;
		MUTEX_LOCK(&pList->lock);
		LIST_VOID_MEM_T::iterator it;
		for (it = pList->list.begin(); it != pList->list.end(); it++){
			if ((unsigned int)((LPST_AUDIO_FRAME_T)(*it))->seq >= pFrame->seq){
				if ((pFrame->timestamp.tv_sec != 0) && ((pFrame->timestamp.tv_sec <= ((LPST_AUDIO_FRAME_T)(*it))->timestamp.tv_sec))){
					bRet = DumpFrame((*it), pDest);
					break;
				}
				else if (pFrame->timestamp.tv_sec == 0){
					bRet = DumpFrame((*it), pDest);
					break;
				}
			}
		}
		MUTEX_UNLOCK(&pList->lock);
	}
	else if (nType == TYPE_VIDEO_FRAME){
		LPST_VIDEO_FRAME_T pFrame = (LPST_VIDEO_FRAME_T)pDest;
		MUTEX_LOCK(&pList->lock);
		LIST_VOID_MEM_T::iterator it;
		for (it = pList->list.begin(); it != pList->list.end(); it++){
			if ((unsigned int)((LPST_VIDEO_FRAME_T)(*it))->seq >= pFrame->seq){
				bRet = DumpFrame((*it), pDest);
				break;
			}
		}
		MUTEX_UNLOCK(&pList->lock);
	}
	return bRet;
}

